import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;

@WebServlet("/Login")
public class Loginservlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        super.doGet(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("收到登录表单请求");
        //1.获取参数
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String remember=request.getParameter("rememberMe");

        ServletContext context=request.getServletContext();
        Object userInDB=context.getAttribute("users");
        if(userInDB==null){
            request.setAttribute("msg","当前用户名未注册!");
            request.getRequestDispatcher("/Login.jsp").forward(request,response);
        }else {
            HashMap<String, String> users = (HashMap<String, String>) userInDB;
            if (users.containsKey(username)) {
                if (users.get(username).equals(password)) {
                    if ("yes".equals(remember)) {
                        Cookie usernameCookie = new Cookie("username", username);
                        Cookie passwordCookie = new Cookie("password", password);
                        usernameCookie.setMaxAge(60 * 60 * 24 * 7);
                        passwordCookie.setMaxAge(60 * 60 * 24 * 7);
                        response.addCookie(usernameCookie);
                        response.addCookie(passwordCookie);
                    }
                    HttpSession session = request.getSession();
                    session.setAttribute("username", username);

                    response.sendRedirect(request.getContextPath() + "/home.jsp");
                } else {
                    request.setAttribute("msg", "密码错误");
                    request.getRequestDispatcher("/Login.jsp").forward(request, response);
                }

            } else {
                request.setAttribute("msg","当前用户名未注册！");
                request.getRequestDispatcher("/Login.jsp").forward(request,response);

            }
        }
    }
}